import "./BrowseHistory.scss";
import type { stepPerson } from "../PersonCenter";
import RetrunLast from "./RetrunLast";
import { postLookHistory } from "@s/api/apis";
import { useEffect, useState } from "react";
import { Timeline } from "antd";
type Thistory = {
  abstract: String;
  title: String;
  viewTime: String;
};
function BrowseHistory(props: { toSetStep: (val: stepPerson) => void }) {
  const { toSetStep } = props;
  const [dataList, setDataList] = useState<Thistory[]>();
  // 去重
  function removeDuplicatesByTitle(arr: Thistory[]) {
    const uniqueMap = new Map();
    arr.forEach((item: Thistory) => {
      if (!uniqueMap.has(item.title)) {
        uniqueMap.set(item.title, item);
      }
    });
    return Array.from(uniqueMap.values()) as unknown as Thistory[];
  }

  // 转换函数
  function transformHistory(
    history: Thistory[]
  ): { label: string; children: string }[] {
    // 使用reduce聚合数据
    const transformedData = history.reduce((acc, current) => {
      // 如果label（即时间）不存在于累加器中，则创建新条目
      if (!acc[current.viewTime]) {
        acc[current.viewTime] = {
          label: current.viewTime,
          children: `${current.title}: ${current.abstract}`,
        };
      } else {
        // 如果label已存在，则将当前条目的title和abstract添加到现有children中
        // 注意：此处假设children需要累积多个title和abstract，实际情况可能需要调整格式
        acc[
          current.viewTime
        ].children += `\n${current.title}: ${current.abstract}`;
      }
      return acc;
    }, {});

    // 将对象转换为期望的数组格式并返回
    return Object.values(transformedData);
  }
  useEffect(() => {
    postLookHistory({
      userName: localStorage.getItem("userName"),
    }).then((res) => {
      setDataList(removeDuplicatesByTitle(res as any));
    });
  }, []);
  return (
    <div className="BrowseHistoryRoot">
      <RetrunLast toSetStep={toSetStep}></RetrunLast>
      <Timeline className="timeLine" mode={"left"} items={transformHistory(dataList || [])} />
    </div>
  );
}

export default BrowseHistory;
